document.addEventListener('DOMContentLoaded', function() {
    const toggleSwitch = document.getElementById('toggleSwitch');
    const statusIcon = document.getElementById('statusIcon');
    const statusText = document.getElementById('statusText');

    // 获取当前状态
    chrome.runtime.sendMessage({ action: "getState" })
        .then(response => {
            if (response) {
                toggleSwitch.checked = response.enabled;
                updateUI(response.enabled);
            }
        })
        .catch(error => {
            console.log('Failed to get initial state:', error);
            // 默认启用
            toggleSwitch.checked = true;
            updateUI(true);
        });

    // 处理开关切换
    toggleSwitch.addEventListener('change', function() {
        chrome.runtime.sendMessage({ action: "toggleState" })
            .then(response => {
                if (response) {
                    updateUI(response.enabled);
                }
            })
            .catch(error => {
                console.log('Failed to toggle state:', error);
                // 回滚UI状态
                toggleSwitch.checked = !toggleSwitch.checked;
                updateUI(toggleSwitch.checked);
            });
    });

    // 更新UI显示
    function updateUI(enabled) {
        if (enabled) {
            statusIcon.className = 'status-icon enabled';
            statusText.textContent = '已启用复制功能';
        } else {
            statusIcon.className = 'status-icon disabled';
            statusText.textContent = '已禁用复制功能';
        }
    }
});
